package com.paiai.lslease.service.appuser;

import com.dsmzg.base.constants.BaseConstants;
import com.dsmzg.base.util.push.SMSPushSwitcher;
import com.dsmzg.base.util.push.sms.CallableSMSPush;
import com.dsmzg.base.util.time.TimeUtil;
import com.paiai.lslease.auto.dao.AppMessageCodeDAO;
import com.paiai.lslease.auto.dao.AppSysUserDAO;
import com.paiai.lslease.auto.model.AppMessageCode;
import com.paiai.lslease.auto.model.AppMessageCodeExample;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.auto.model.AppSysUserExample;
import com.paiai.lslease.base.SystemConstants;
import com.paiai.lslease.service.BaseServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class AppMessageCodeServiceImpl implements AppMessageCodeService {

    private static final Logger logger = LoggerFactory.getLogger(AppMessageCodeServiceImpl.class);

    private AppMessageCodeDAO appMessageCodeDAO;

    public void setAppMessageCodeDAO(AppMessageCodeDAO appMessageCodeDAO) {
        this.appMessageCodeDAO = appMessageCodeDAO;
    }

    public String getMessageCode(String userAccount) throws Exception {
        int messageCode;
        try {
//            //查询用户是否已经绑定微信账号
//            AppSysUserExample appSysUserExample = new AppSysUserExample();
//            appSysUserExample.createCriteria().andMobileEqualTo(userAccount);
//            List<AppSysUser> appSysUserList = appSysUserDAO.selectByExample(appSysUserExample);
//            if (appSysUserList != null && appSysUserList.size() > 0) {//已经绑定微信账号
//                return "已经绑定了微信账号，请不要重复绑定";
//            }
            //查询用户1分钟内有没有未使用的验证码
            AppMessageCodeExample appMessageCodeExample = new AppMessageCodeExample();
            appMessageCodeExample.createCriteria().andUserMobileAccountEqualTo(userAccount).andMsgstateEqualTo(1).andInsertTimeGreaterThan(new Date(System.currentTimeMillis() - 60 * 1000));
            List<AppMessageCode> appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
            if (appMessageCodeList != null && appMessageCodeList.size() > 0) {//1分钟内有未使用的验证码，直接返回
                return "1分钟内有未使用的验证码";
            }
            //1分钟内没有未使用的验证码，检查用户今天一共发送了多少条短信
            appMessageCodeExample = new AppMessageCodeExample();
            appMessageCodeExample.createCriteria().andUserMobileAccountEqualTo(userAccount).andInsertTimeGreaterThan(new Date(TimeUtil.getBeginStamp() * 1000));
            appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
            if (appMessageCodeList.size() >= 5) {//用户今天发送的短信条数已超过5条
                return "用户今天发送的短信条数已超过5条,共发送了" + appMessageCodeList.size() + "条";
            }
            //用户今天发送的短信条数没有超过5条，生成一个新的验证码发送给用户
            messageCode = (int) (Math.random() * 9000) + 999;
            Map<String,String> smsVarMap = new HashMap<String,String>();
            smsVarMap.put("code", messageCode + "");
            smsVarMap.put("product", "");
            CallableSMSPush callableSMSPush = new CallableSMSPush(userAccount, SystemConstants.smsTemplateMap.get("116"), smsVarMap,userAccount+"(用户注册)");
            String callableMsg = SMSPushSwitcher.CallableMsg(callableSMSPush);
            if(!BaseConstants.RES_SEND_SUCCEED.equalsIgnoreCase(callableMsg)){
                return "发送短信出错";
            }
            markMessageCodeInvalid(userAccount);
            AppMessageCode appMessageCode = new AppMessageCode();
            appMessageCode.setUserMobileAccount(userAccount);
            appMessageCode.setUserShortNum(messageCode + "");
            appMessageCode.setMsgstate(1);
            appMessageCode.setInsertTime(new Date());
            appMessageCode.setUpdateTime(appMessageCode.getInsertTime());
            appMessageCode.setRemark("注册用户获取验证码");
            appMessageCodeDAO.insert(appMessageCode);
        } catch (Exception e) {
            return "获取验证码出错";
        }
        return messageCode + "";
    }

    public String checkMessageCode(AppMessageCode appMessageCode) throws Exception {
        //验证验证码是否正确，先获取用户未使用的验证码数据
        AppMessageCodeExample appMessageCodeExample = new AppMessageCodeExample();
        AppMessageCodeExample.Criteria criteria = appMessageCodeExample.createCriteria().andUserMobileAccountEqualTo(appMessageCode.getUserMobileAccount()).andMsgstateEqualTo(1);
        List<AppMessageCode> appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
        if (appMessageCodeList == null || appMessageCodeList.size() == 0) {//没有未使用的验证码
            return "没有未使用的验证码，请先获取验证码";
        }
        criteria.andUserShortNumEqualTo(appMessageCode.getUserShortNum());
        appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
        if (appMessageCodeList == null || appMessageCodeList.size() == 0) {
            return "验证码错误";
        }
        criteria.andInsertTimeLessThan(new Date(System.currentTimeMillis() - 60*1000));
        appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
        if (appMessageCodeList != null && appMessageCodeList.size() > 0) {
            return "验证码过期，请重新获取";
        }
        //有未使用的验证码，更新验证码状态为已使用，返回验证成功
        AppMessageCodeExample appMessageCodeExample_ = new AppMessageCodeExample();
        appMessageCodeExample.createCriteria().andUserMobileAccountEqualTo(appMessageCode.getUserMobileAccount()).andUserShortNumEqualTo(appMessageCode.getUserShortNum()).andMsgstateEqualTo(1);
        AppMessageCode appMessageCode_ = new AppMessageCode();
        appMessageCode_.setMsgstate(2);
        appMessageCode_.setUpdateTime(new Date());
        appMessageCode_.setRemark("验证验证码");
        int rows = appMessageCodeDAO.updateByExampleSelective(appMessageCode_, appMessageCodeExample_);
        if (rows <= 0) {
            return "验证码校验失败";
        }
        return null;
    }

    /**
     * 当前用户的所有标记为未使用的验证码标记为已使用
     */
    private void markMessageCodeInvalid(String userMobile) throws Exception {
        AppMessageCodeExample appMessageCodeExample = new AppMessageCodeExample();
        appMessageCodeExample.createCriteria().andUserMobileAccountEqualTo(userMobile).andMsgstateEqualTo(1);
        List<AppMessageCode> appMessageCodeList = appMessageCodeDAO.selectByExample(appMessageCodeExample);
        for (AppMessageCode appMessageCode : appMessageCodeList) {
            appMessageCode.setMsgstate(2);
            appMessageCode.setUpdateTime(new Date());
            appMessageCode.setRemark("验证码过期取消");
            appMessageCodeDAO.updateByPrimaryKey(appMessageCode);
        }
    }
}
